package com.service.impl;

import com.dao.GroupInfoDao;
import com.dao.GroupUserDao;
import com.dao.GroupVerifyMessageDao;
import com.dao.UserInfoDao;
import com.entity.GroupUser;
import com.entity.GroupVerifyMessage;
import com.service.GroupVerifyMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 群验证业务实现
 *
 * @author lbb
 * @version 1.0
 * @date 2020.3.22
 */
@Service
public class GroupVerifyMessageServiceImpl implements GroupVerifyMessageService {
	//群验证
	@Autowired
	private GroupVerifyMessageDao groupVerifyMessageDao;
	//群成员
	@Autowired
	private GroupUserDao groupUserDao;
	@Autowired
	private GroupInfoDao groupInfoDao;
	@Autowired
	private UserInfoDao userInfoDao;
	
	//添加
	@Override
	@Transactional
	public Boolean addGroupVerifyMessage(GroupVerifyMessage groupVerifyMessage) {
		//判断如果数量大于0，则表示重复发送请求
		if(groupVerifyMessageDao.getNotDisposeCount(groupVerifyMessage)>0){
			return false;
		}
		groupVerifyMessageDao.addGroupVerifyMessage(groupVerifyMessage);

		return true;
	}
	//按照群id查询
	@Override
	@Transactional
	public List<GroupVerifyMessage> getByToGroupIdAllGroupVerifyMessage(Integer pageNum,Integer pageSize,Integer toGroupId) {
		List<GroupVerifyMessage> results = groupVerifyMessageDao.getByToGroupIdAllGroupVerifyMessage(pageNum,pageSize,toGroupId);
		for (GroupVerifyMessage result : results) {
			//查找用户信息并设置用户信息
			result.setFromUserInfo(userInfoDao.getById(result.getFromUserId()));
		}
		return results;
	}
	//按照用户id查询
	@Override
	@Transactional
	public List<GroupVerifyMessage> getByToUserIdAllGroupVerifyMessage(Integer pageNum,Integer pageSize,Integer fromUserId) {
		List<GroupVerifyMessage> results = groupVerifyMessageDao.getByToUserIdAllGroupVerifyMessage(pageNum,pageSize,fromUserId);
		for (GroupVerifyMessage result : results) {
			//查找群信息并设置群信息
			result.setToGroupInfo(groupInfoDao.getById(result.getToGroupId()));
		}
		return results;
	}

	//修改状态
	@Override
	public Boolean editStatus(GroupVerifyMessage groupVerifyMessage) {
		if(groupVerifyMessage.getStatus().equals(1)){//表示同意
			//判断是否有此群成员信息
			GroupUser groupUser = groupUserDao.getByUserIdWithGroupId(groupVerifyMessage.getFromUserId(), groupVerifyMessage.getToGroupId());
			if(groupUser == null) {//如果没有则添加一条
				groupUser = new GroupUser();
				groupUser.setUserId(groupVerifyMessage.getFromUserId());
				groupUser.setGroupId(groupVerifyMessage.getToGroupId());
				groupUser.setNoteName("");
				groupUser.setIsSilent(0);
				groupUser.setGroupRole(2);
				groupUser.setNotReadCount(0);
				groupUser.setIsRemove(0);
				groupUserDao.addGroupUser(groupUser);
			}else {//如果有就修改一下删除状态
				groupUser.setIsRemove(0);
				groupUser.setJoinTime(new Date());
				groupUserDao.editGroupUser(groupUser);
			}
		}
		return groupVerifyMessageDao.editStatus(groupVerifyMessage);
	}
}
